package com.bdf.ipharma.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.LineBorder;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import org.apache.log4j.Logger;

import com.bdf.ipharma.components.CustomHeaderTable;
import com.bdf.ipharma.config.Session;
import com.bdf.ipharma.dto.PairValue;
import com.bdf.ipharma.gui.helper.GuiExtraccion2Helper;
import com.bdf.ipharma.model.ProductoModel;
import com.bdf.ipharma.model.map.ProductoStockMap;
import com.bdf.ipharma.renderers.JTableButtonRenderer;
import com.bdf.ipharma.starter.McdMain;
import com.bdf.ipharma.starter.McdPrs;

public class GuiExtraction2 extends GUIWindow {

	public Session session;

	static final Logger logger = Logger.getLogger(GuiExtraction2.class);
	private JPanel tableContainer;
	private RoundedPanel contentTableRoundedPanel;
	private JPanel bodyContent;
	private GroupLayout gl_bodyContent;
	private McdMain mcdMain;
	private JScrollPane tableScrolPane;
	private GroupLayout gl_contentTableRoundedPanel;
	private JTable productTable;
	public boolean isTableEnabled;
	private JComboBox  jACComboBox;
	private GUIButtonImage jBtnExtraer;
	private GUIButtonImage jBtnCancelar;
	private RoundedPanel roundedPanel;
	private GroupLayout gl_roundedPanel;
	private JLabel selectedItem;
	
	PairValue[] listUsuarioAutocompleter = null;
	
	public GuiExtraction2(McdMain mcdMain) {
		super(mcdMain);
		try {
			this.mcdMain = mcdMain;
			this.session = mcdMain.getSession();
			
			/** Chequeo si tengo productos, si no tengo, vuelvo al login desplegando un mensaje**/
			

			/** fin **/
			init(mcdMain);
		} catch (Exception e) {
			logger.fatal(e.getMessage());
		}
	}

	private void init(McdMain mcdMain) {

		
		this.setSize(800, 650);
		this.setBackground(new Color(255, 255, 255));

		bodyContent = new JPanel();
		bodyContent.setBackground(new Color(255, 255, 255));
		bodyContent.setSize(800, 450);
		bodyContent.setOpaque(false);

		// Inicializo el Header
		GUIHeaderComponent headerComponent = new GUIHeaderComponent(mcdMain);

		GroupLayout groupLayout = new GroupLayout(this);
		groupLayout.setHorizontalGroup(
			groupLayout.createParallelGroup(Alignment.TRAILING)
				.addComponent(headerComponent, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
				.addGroup(groupLayout.createSequentialGroup()
					.addContainerGap()
					.addComponent(bodyContent, GroupLayout.DEFAULT_SIZE, 790, Short.MAX_VALUE)
					.addContainerGap())
		);
		groupLayout.setVerticalGroup(
			groupLayout.createParallelGroup(Alignment.LEADING)
				.addGroup(groupLayout.createSequentialGroup()
					.addComponent(headerComponent, GroupLayout.PREFERRED_SIZE, 82, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(bodyContent, GroupLayout.DEFAULT_SIZE, 528, Short.MAX_VALUE)
					.addGap(34))
		);

		contentTableRoundedPanel = new RoundedPanel();
		contentTableRoundedPanel.setBackground(new Color(255, 255, 255));
		contentTableRoundedPanel.setImg(Images.bgProductosPanel.getImage());
		
		JLabel lblNewLabel = new JLabel("Funcion   >  Extraer ");

		roundedPanel= new RoundedPanel();
		roundedPanel.setBackground(new Color(255, 255, 255));
		roundedPanel.setImg(Images.bgAsignacionPanel.getImage());

		jBtnExtraer = new GUIButtonImage("Extraer", Images.buttOk, Images.buttOkDn);
		jBtnExtraer.setEnabled(false);

		jBtnExtraer.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				logger.debug("*** COMIENZO DE LA EXTRACCION ***");
				
				try {
					/**Controlo la session **/
					theSess.isTimeout(new Date());
					theSess.setTimeout(new Date());
					
					
					GuiExtraccion2Helper helper = new GuiExtraccion2Helper();	
					helper.setMcdMain(GuiExtraction2.this.mcdMain);
					
					/** Extrae los productos del dispenser y devuelve la lista para extraer en la base **/
					List<ProductoStockMap> listaProdAExtraerDB = helper.extraccion(session, e);
					
					/** Extraer la lista de productos en la base de datos. **/
					helper.extraerProductoDataBase(listaProdAExtraerDB, session, e, jACComboBox.getSelectedItem());
					
					/** Limpia la tabla para mostrar en pantalla**/
					limpiarTabla();

					/**Borra todos los elementos de session **/
					session.disposeSession();

					logger.debug("*** FIN DE LA EXTRACCION ***");
					
				} catch (Exception exceptionExtraccion) {
					if(exceptionExtraccion.getMessage().equalsIgnoreCase(Texts.MENSAJE_SESSION_TIMEOUT)){
						JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent((Component) e.getSource()),
								Texts.MENSAJE_SESSION_TIMEOUT);
						session.disposeSession();
						GuiExtraction2.this.mcdMain.start();							
					}
					else if(exceptionExtraccion.getMessage().equalsIgnoreCase(McdPrs.MENSAJE_ERROR_SIN_PRODUCTOS_EXTRACCION)){
						JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent((Component) e.getSource()),
								McdPrs.MENSAJE_ERROR_SIN_PRODUCTOS_EXTRACCION);
						session.disposeSession();
						GuiExtraction2.this.mcdMain.start();
					}else{
						JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent((Component) e.getSource()),
								exceptionExtraccion.getMessage());						
					}

					logger.fatal("*** ERROR DE EXTRACCION  ***");	
				}

				GuiExtraction2.this.mcdMain.start();												
			}
		}
		);

		jBtnCancelar= new GUIButtonImage("Cancelar", Images.buttOk, Images.buttOkDn);
		jBtnCancelar.setEnabled(false);
		jBtnCancelar.addActionListener(new ActionListener() {
			
			public void actionPerformed(ActionEvent e) {				
				System.out.println("cancelando...");
				limpiarTabla();
				contentTableRoundedPanel.validate();
				contentTableRoundedPanel.repaint();
				
				session.disposeSession();
				GuiExtraction2.this.mcdMain.start();
			}
		});
		gl_bodyContent = new GroupLayout(bodyContent);
		gl_bodyContent.setHorizontalGroup(
			gl_bodyContent.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_bodyContent.createSequentialGroup()
					.addGroup(gl_bodyContent.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_bodyContent.createSequentialGroup()
							.addContainerGap()
							.addComponent(lblNewLabel, GroupLayout.PREFERRED_SIZE, 198, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_bodyContent.createSequentialGroup()
							.addGap(135)
							.addComponent(roundedPanel, GroupLayout.PREFERRED_SIZE, 520, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_bodyContent.createSequentialGroup()
							.addGap(101)
							.addGroup(gl_bodyContent.createParallelGroup(Alignment.TRAILING)
								.addComponent(contentTableRoundedPanel, GroupLayout.PREFERRED_SIZE, 588, GroupLayout.PREFERRED_SIZE)
								.addGroup(gl_bodyContent.createSequentialGroup()
									.addComponent(jBtnCancelar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(jBtnExtraer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))))
					.addContainerGap(101, Short.MAX_VALUE))
		);
		gl_bodyContent.setVerticalGroup(
			gl_bodyContent.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_bodyContent.createSequentialGroup()
					.addComponent(lblNewLabel)
					.addGap(8)
					.addComponent(roundedPanel, GroupLayout.PREFERRED_SIZE, 73, GroupLayout.PREFERRED_SIZE)
					.addGap(11)
					.addComponent(contentTableRoundedPanel, GroupLayout.PREFERRED_SIZE, 323, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_bodyContent.createParallelGroup(Alignment.BASELINE)
						.addComponent(jBtnExtraer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(jBtnCancelar, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(93, Short.MAX_VALUE))
		);

		GuiExtraccion2Helper helper = new GuiExtraccion2Helper();
		try {
			this.listUsuarioAutocompleter = helper.getAsignaciones(session);
		} catch (Exception exceptionAsignaciones) {
			//FIXME poner la excepcion en mensaje. 
			logger.fatal(exceptionAsignaciones.getMessage());
			System.out.println("FIX ME EXCEPTION");
		}

		jACComboBox= new ACJComboBox(listUsuarioAutocompleter);
		jACComboBox.setEditable(false);
		jACComboBox.setSelectedItem(new PairValue("","blank"));
		selectedItem = new JLabel("");
		selectedItem.setVisible(false);
		setRoundedPanelLayout();
		roundedPanel.setLayout(gl_roundedPanel);
		tableContainer = new JPanel();
		initTable(false);
		
		gl_contentTableRoundedPanel = new GroupLayout(contentTableRoundedPanel);
		gl_contentTableRoundedPanel.setHorizontalGroup(
			gl_contentTableRoundedPanel.createParallelGroup(Alignment.LEADING)
				.addComponent(tableContainer, GroupLayout.PREFERRED_SIZE, 0, GroupLayout.PREFERRED_SIZE)
				.addGroup(gl_contentTableRoundedPanel.createSequentialGroup()
					.addContainerGap()
					.addComponent(tableScrolPane, GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE)
					.addContainerGap())
		);
		gl_contentTableRoundedPanel.setVerticalGroup(
			gl_contentTableRoundedPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentTableRoundedPanel.createSequentialGroup()
					.addGroup(gl_contentTableRoundedPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(tableContainer, GroupLayout.PREFERRED_SIZE, 0, GroupLayout.PREFERRED_SIZE)
						.addGroup(Alignment.TRAILING, gl_contentTableRoundedPanel.createSequentialGroup()
							.addContainerGap(27, Short.MAX_VALUE)
							.addComponent(tableScrolPane, GroupLayout.PREFERRED_SIZE, 290, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap())
		);
		contentTableRoundedPanel.setLayout(gl_contentTableRoundedPanel);
		
		
		setLayout(groupLayout);
		
		jACComboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(jACComboBox.getSelectedItem()!=null){
					PairValue pairValue = (PairValue) jACComboBox.getSelectedItem();
					jACComboBox.setVisible(false);
					selectedItem.setText(pairValue.getKey());
					selectedItem.setVisible(true);
					setRoundedPanelLayout();
					roundedPanel.repaint();
					roundedPanel.validate();
					//jACComboBox.setEditable(false);
//					jACComboBox.setEnabled(false);
//					jACComboBox.setFont(new Font("Sanserif", Font.BOLD,18));
//					jACComboBox.setBackground(Color.white);
//     				jACComboBox.setForeground(Color.black);
					initTable(true);
					jBtnCancelar.setEnabled(true);
					jBtnExtraer.setEnabled(true);
					contentTableRoundedPanel.repaint();
					contentTableRoundedPanel.validate();
				}	
			}
		});
	}

	/** LImpia la tabla despues de CANCELAR O EXTRAER. **/
	private void limpiarTabla() {
		List<ProductoStockMap> sessionList = (List<ProductoStockMap>) session.get(McdPrs.PRODUCTOS_SELECCIONADOS);
		boolean isChanged = false;
		for (ProductoStockMap productoStockMap : sessionList) {
			if(productoStockMap.getCantidadAExtraer() > 0){
				isChanged = true;
				productoStockMap.setCantidadAExtraer(0);
			}
		}
		
		if(isChanged){
			session.remove(McdPrs.PRODUCTOS_SELECCIONADOS);
			session.put(McdPrs.PRODUCTOS_SELECCIONADOS, sessionList);
			initTable(true);
		}else{
			JOptionPane.showMessageDialog(
					JOptionPane.getFrameForComponent(this),
					"No existen extracciones pendientes.");
			
			mcdMain.getSession().disposeSession();
			this.mcdMain.start();
		}		
	}	

	public  void initTable(boolean enabled) {
		this.isTableEnabled = enabled;
		this.session.put(McdPrs.COMP_ENABLED, this.isTableEnabled);
		if(tableContainer!=null){
			tableContainer.removeAll();
			tableContainer.validate();
			tableContainer.repaint();
		}
		productTable = new JTable(new ProductoModel(this.session, this)) {
			
			
			public Component prepareRenderer(TableCellRenderer renderer, int Index_row, int Index_col) {
				Component comp = super.prepareRenderer(renderer, Index_row, Index_col);

				if (Index_row % 2 == 0 && !isCellSelected(Index_row, Index_col)) {
					comp.setBackground(new Color(30, 144, 255));
					comp.setForeground(Color.white);
				} else {
					comp.setBackground(Color.white);
					comp.setForeground(new Color(46, 139, 87));
				}
				if (isCellSelected(Index_row, Index_col)) {

					comp.setBackground(Color.lightGray);
					comp.setForeground(Color.black);
				}
				if(!comp.isEnabled()){
					comp.setBackground(Color.lightGray);
					comp.setForeground(Color.black);
					comp.setFont(new Font("Sanserif", Font.BOLD,14));
				}	
				comp.setEnabled(GuiExtraction2.this.isTableEnabled);
				return comp;
			}
			
		
		};
		
		 TableColumn col1 = productTable.getColumnModel().getColumn(0);
		 TableColumn col2 = productTable.getColumnModel().getColumn(1);
		 TableColumn col3 = productTable.getColumnModel().getColumn(2);
		 TableColumn col4 = productTable.getColumnModel().getColumn(3);
		 col1.setHeaderRenderer(new CustomHeaderTable());
		 col2.setHeaderRenderer(new CustomHeaderTable());
		 col3.setHeaderRenderer(new CustomHeaderTable());
		 col4.setHeaderRenderer(new CustomHeaderTable());
		 
		
		productTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		productTable.getColumnModel().getColumn(0).setPreferredWidth(280);
		productTable.getColumnModel().getColumn(1).setPreferredWidth(50);
		productTable.getColumnModel().getColumn(2).setPreferredWidth(120);
		productTable.getColumnModel().getColumn(3).setPreferredWidth(111);
		productTable.setRowHeight(50);

		productTable.getColumn("Extraer").setCellRenderer(new JTableButtonRenderer(this));
		productTable.getColumn("Extraer").setCellEditor(new JTableButtonRenderer(this));
		//productTable.addMouseListener(new JTableButtonMouseListener(productTable,this.session));
		Dimension dim = new Dimension(20, 1);


		JTableHeader header = productTable.getTableHeader();
		header.setBackground(Color.white);
		header.setBorder(new LineBorder(Color.lightGray, 1, true));
		header.setResizingAllowed(false);
		header.setReorderingAllowed(false);

		productTable.setForeground(Color.GRAY);
		productTable.setFont(new Font("Tahoma", Font.CENTER_BASELINE, 12));

		productTable.setShowVerticalLines(false);
		productTable.setShowHorizontalLines(false);
		productTable.setShowGrid(false);
		productTable.setBackground(Color.white);
		
		tableScrolPane = new JScrollPane(productTable);
		tableContainer.setOpaque(false);
		
		
		
		tableContainer.add(tableScrolPane);
		contentTableRoundedPanel.setOpaque(false);
		contentTableRoundedPanel.setLayout(gl_contentTableRoundedPanel);
		bodyContent.setLayout(gl_bodyContent);
		contentTableRoundedPanel.validate();
		contentTableRoundedPanel.repaint();
		
	}

	public PairValue[] getListUsuarioAutocompleter() {
		return listUsuarioAutocompleter;
	}

	public void setListUsuarioAutocompleter(PairValue[] listUsuarioAutocompleter) {
		this.listUsuarioAutocompleter = listUsuarioAutocompleter;
	}

	public void paintComponent(Graphics g) {
		g.drawImage(Images.footerIpharma.getImage(), 0, 20, null);

	}

	private void setRoundedPanelLayout (){
		JLabel jLblAsignacion = new JLabel(Texts.EXT_LBL_ASIGNACION);
		jLblAsignacion.setForeground(new Color(255, 255, 255));
		gl_roundedPanel = new GroupLayout(roundedPanel);
		gl_roundedPanel.setHorizontalGroup(
			gl_roundedPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_roundedPanel.createSequentialGroup()
					.addGroup(gl_roundedPanel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_roundedPanel.createSequentialGroup()
							.addContainerGap()
							.addComponent(jLblAsignacion, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_roundedPanel.createSequentialGroup()
							.addGap(16)
							.addComponent(jACComboBox, GroupLayout.PREFERRED_SIZE, 488, GroupLayout.PREFERRED_SIZE)
							.addComponent(selectedItem, GroupLayout.PREFERRED_SIZE, 488, GroupLayout.PREFERRED_SIZE))
							)
					.addContainerGap(16, Short.MAX_VALUE))
		);
		gl_roundedPanel.setVerticalGroup(
			gl_roundedPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_roundedPanel.createSequentialGroup()
					.addComponent(jLblAsignacion)
					.addGap(11)
					.addComponent(jACComboBox, GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
					.addComponent(selectedItem, GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
					.addContainerGap())
		);
	}
	
	private static final long serialVersionUID = 1L;
}
